const { Bluetooth } = require('electron-bluetooth');

class BluetoothManager {
    constructor() {
        this.bluetooth = new Bluetooth();
        this.deviceInstances = new Map(); // 存储设备实例
        this.receiveCallbacks = new Map(); // 存储接收回调
        this.breakCallbacks = new Map(); // 存储断开连接回调
    }

    /**
     * 初始化并连接蓝牙设备
     * @param {number} index - 设备索引
     * @param {string} serviceUuid - 服务UUID
     * @param {string} txCharUuid - 发送特征UUID
     * @param {string} rxCharUuid - 接收特征UUID
     * @param {string} deviceName - 设备名称或前缀
     */
    async initBle(index, serviceUuid, txCharUuid, rxCharUuid, deviceName) {
        try {

            // 发现设备
            const devices = await this.bluetooth.findDevices({
                name: deviceName // 或使用 namePrefix 如果支持
            });

            if (devices.length === 0) {
                throw new Error('未找到匹配的设备');
            }

            // 连接第一个匹配的设备
            const device = await this.bluetooth.connect(devices[0].id);

            // 获取服务
            const service = await device.discoverServices([serviceUuid]);
            if (service.length === 0) {
                throw new Error('未找到指定的服务');
            }

            // 获取特征
            const txChar = await this.findCharacteristic(service[0], txCharUuid, 'write');
            const rxChar = await this.findCharacteristic(service[0], rxCharUuid, 'notify');

            if (!txChar || !rxChar) {
                throw new Error('未找到指定的特征');
            }

            // 存储设备实例
            this.deviceInstances.set(index, { device, txChar, rxChar });

            // 设置接收监听
            rxChar.on('data', (data) => {
                if (this.receiveCallbacks.has(index)) {
                    this.receiveCallbacks.get(index)(data.toString('utf8'), index);
                }
            });

            // 设置断开连接监听
            device.on('close', () => {
                if (this.breakCallbacks.has(index)) {
                    this.breakCallbacks.get(index)();
                }
                this.deviceInstances.delete(index);
            });

            return true;
        } catch (error) {
            console.error(`设备 ${index + 1} 连接失败:`, error);
            return false;
        }
    }

    /**
     * 发送数据到设备
     * @param {number} index - 设备索引
     * @param {string|Buffer} data - 要发送的数据
     * @param {function} errorCallback - 错误回调函数
     * @param {function} successCallback - 发送成功回调函数
     */
    async sendData(index, data) {
        const instance = this.deviceInstances.get(index);
        if (!instance) {
            console.error(`设备 ${index + 1} 未连接`);
            return;
        }
        await instance.txChar.write(Buffer.isBuffer(data));
    }

    /**
     * 设置回调函数
     * @param {number} index - 设备索引
     * @param {function} receiveFun - 接收数据回调
     * @param {function} breakFun - 断开连接回调
     * @param {function} errorFun - 错误回调
     * @param {function} dataSentFun - 数据发送成功回调
     * @param {function} disconnectedFun - 断开连接回调
     */
    setCallbacks(index, receiveFun, breakFun) {
        if (receiveFun) {
            this.receiveCallbacks.set(index, receiveFun);
        }
        if (breakFun) {
            this.breakCallbacks.set(index, breakFun);
        }
    }

    /**
     * 断开设备连接
     * @param {number} index - 设备索引
     * @param {function} errorCallback - 错误回调函数
     */
    async disconnect(index) {
        const instance = this.deviceInstances.get(index);
        if (instance) {
            await instance.device.close();
            this.deviceInstances.delete(index);
        }
    }
}

module.exports = BluetoothManager;